package com.topisv.tms.web.stock.goods;

import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springside.modules.web.Servlets;

import com.topisv.tms.entity.Customers;
import com.topisv.tms.entity.EdiGoodsSku;
import com.topisv.tms.entity.JSONParam;
import com.topisv.tms.entity.QueryParamHolder;
import com.topisv.tms.entity.stock.CusStock;
import com.topisv.tms.service.CustomersService;
import com.topisv.tms.service.EdiGoodsSkuService;
import com.topisv.tms.service.account.ShiroDbRealm.ShiroUser;
import com.topisv.tms.tools.DataTablesUtils;
import com.topisv.tms.tools.ExcelUtils;
import com.topisv.tms.utils.JsonUtil;
import com.topisv.tms.web.base.BaseDataTableController;

/**
 * 商品_control
 * @author ch
 */
@Controller
@RequestMapping({ "/goods" })
public class GoodsController extends BaseDataTableController{

	private static final Logger logger = LoggerFactory.getLogger(GoodsController.class);
	private static final int PAGE_SIZE = 30;
	
	@Autowired
	private CustomersService customersService;
	@Autowired
	private EdiGoodsSkuService ediGoodsSkuService;

	@RequestMapping(value = "v2_show")
	public String show(Model model){
		fillSelectValue(model, null);
		return "stock/goods/goodsMgr";
	}
	/**
	 * 导向商品管理页面
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "toGoodsMgr")
	public String toGoodsMgr(@RequestParam(value = "page", defaultValue = "1") int pageNumber,Model model, ServletRequest request) {
		try {
			//查出当前用户关联的商家列表
			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			List<Customers> customerList=this.customersService.loadCustomerByAuthority(curUser);
			model.addAttribute("customerList",customerList);
			model.addAttribute("userType",curUser.userType);
			
			//如果是商家用户,初始化数据
			if("customer".equals(curUser.userType)){
				String customerCode = curUser.customerCode;
				model.addAttribute("customerCode", customerCode);
				//商品数据
				Map<String, Object> params = new HashMap<String, Object>();
				params.put("status", "1");
				params.put("customerCode", customerCode);
				Page<EdiGoodsSku> page = this.ediGoodsSkuService.loadGoods(params,pageNumber, PAGE_SIZE);
				model.addAttribute("page", page);
			}
			
		} catch (Exception e) {
			log.error("error",e);
		}
		return "stock/goods/goodsMgr";
	}
	
	/**
	 * 查询商品
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "page")
	public void page(@RequestBody JSONParam[] paramJson, HttpServletRequest request,HttpServletResponse response){
		try {
			// 客户端参数
			QueryParamHolder paramHolder = collectParam(paramJson,"_");
			// 查询商品
			Page<EdiGoodsSku> page = this.ediGoodsSkuService.loadGoods(paramHolder);
			response.getWriter().print(bulidJSON(page));
		} catch (Exception e) {
			log.error("error",e);
		}
	}
	
	/**
	 * 修改商品重量
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value={"ajaxUpdateWeight"}, method={RequestMethod.POST})
	@ResponseBody
	public String ajaxUpdateWeight(ServletRequest request,HttpServletResponse response) {
	    try {
	      Long goodsId = Long.valueOf(request.getParameter("goodsId"));
	      Integer weight = Integer.valueOf(request.getParameter("weight"));
	      this.ediGoodsSkuService.updateWeight(goodsId, weight);
	      return "true";
	    } catch (Exception e) {
	    	
			log.error("error",e);
			return "false";
	    }
	}
	
	/**
	 * 修改包装重量
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value={"ajaxUpdateWeightPkg"}, method={RequestMethod.POST})
	@ResponseBody
	public String ajaxUpdateWeightPkg(ServletRequest request,HttpServletResponse response) {
	    try {
	      Long goodsId = Long.valueOf(request.getParameter("goodsId"));
	      Integer weight = Integer.valueOf(request.getParameter("weight"));
	      this.ediGoodsSkuService.updateWeightPkg(goodsId, weight);
	      return "true";
	    } catch (Exception e) {
	    	
			log.error("error",e);
			return "false";
	    }
	}
	/**
	 * 修改品名
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="ajaxUpdateSkuName", method=RequestMethod.POST)
	@ResponseBody
	public String ajaxUpdateSkuName(ServletRequest request,HttpServletResponse response) {
		try {
			Long goodsId = Long.valueOf(request.getParameter("goodsId"));
			String skuName = request.getParameter("skuName");
			this.ediGoodsSkuService.updateSkuName(goodsId, skuName);
			return "true";
		} catch (Exception e) {
			log.error("error",e);
			return "false";
		}
	}
	
	
	/**
	 * 导出商品信息
	 */
	@RequestMapping(value = "exportExcel")
	public String exportExcel_multi(Model model, ServletRequest request,ServletResponse response){
		FileInputStream f=null;
		OutputStream output=null;
		try {
			Date now=new Date();
			DateFormat df=new SimpleDateFormat("yyyyMMddhhmmss");
			
			// 查询商品
			Map<String, Object> param = Servlets.getParametersStartingWith(request, "_");
			List<EdiGoodsSku> goodsList = this.ediGoodsSkuService.loadGoods(DataTablesUtils.getParamerFromJsonRequest(param));
			
			/** 定义导出数据集合 */
			List<Object[]> list = new ArrayList<Object[]>();
			
			for (int i = 0; i < goodsList.size(); i++) {
				try {
					EdiGoodsSku goods=goodsList.get(i);
					Object[] obj = {
							i+1,
							goods.getCustomer().getCustomerName(),
							goods.getSkuName(),
						    goods.getBar(),
						    goods.getSku(),
						    goods.getHaikwanCode(),
						    goods.getWeight(),
						    goods.getWeightPkg(),
						    goods.getWeightPop(),
						    goods.getSpec(),
						    null
					};
					list.add(obj);
				} catch (Exception e) {
					
					log.error("error",e);
				}
			}
			
			/** 导出数据 */
			String[] title = { "序号", "商家","商品名称","商品货号", "SKU","海关编码","商品重量（g）", "包装重量（g）","泡重","规格参数"};
			String filepath = "ProductInfo.xls";
			String title_page="商品信息表";
			ExcelUtils.writeExcel(title, filepath,title_page, df.format(now) , list); // 生成excel
			
			/** 把生成的excel文件读出字节返回给客户端 */
			((HttpServletResponse)response).setHeader("Content-disposition", "attachment; filename="+ new String(filepath.getBytes("gb2312"),"ISO8859-1"));
			f = new FileInputStream(ExcelUtils.TEMPPATH+filepath);
			byte[] fb = new byte[f.available()];
			f.read(fb);
			ByteArrayInputStream bais = new ByteArrayInputStream(fb);
			output =((HttpServletResponse)response).getOutputStream();
			int by = 0;
			while ((by = bais.read()) != -1) {
				output.write(by);
			}
			output.flush();
			
		} catch (Exception e) {
			return "error";
		}finally{
			if (output!=null) {
				try { output.close(); } catch (IOException e) {log.error("error",e);}
			}
			if (f!=null) {
				try { f.close(); } catch (IOException e)  {log.error("error",e);}
			}
		}
		return null;
	}
	
	/**
	 * 判断商品是否进行批次号或者效期控制
	 * 
	 * @param 
	 * @return 
	 * @throws 
	 * @author Administrator
	 * @version 1.0.0
	 */
	@RequestMapping(value = "checkGoods",method=RequestMethod.POST)
    public void checkGoods(ServletRequest request,HttpServletResponse response) {
	    JSONObject json = null;
        PrintWriter out = null;
        try {

            json = new JSONObject();
            out = response.getWriter();
            
            String status = "error";
            String content = null;
            String isBatchMgmt = null;
            String isShelfLifeMgmt = null;
            
            String customerCode=request.getParameter("customerCode");
            String sku = request.getParameter("sku");
            
            EdiGoodsSku ediGoodsSku = this.ediGoodsSkuService.findByCustomerCodeAndSku(customerCode, sku);
            
            if(ediGoodsSku != null && sku.equals(ediGoodsSku.getSku())){
                isBatchMgmt = ediGoodsSku.getIsBatchMgmt() == null ? "0" : ediGoodsSku.getIsBatchMgmt();
                isShelfLifeMgmt = ediGoodsSku.getIsShelfLifeMgmt() == null ? "0" : ediGoodsSku.getIsShelfLifeMgmt();
                status = "success";
            }else{
                //update LiBin 20161128 bug617
                content = "sku" + sku + "在商家" + customerCode + "下不存在(注意sku大小写!)";
            }
            
            json.put("status", status);
            json.put("content", content);
            json.put("isBatchMgmt", isBatchMgmt);
            json.put("isShelfLifeMgmt", isShelfLifeMgmt);
            
         } catch (Exception e) {
            log.error("error",e);
            json.put("status","error");
            json.put("content",e.getMessage());
        }
        out.print(json.toString());
    }
	
}